//
//  GameRecharge.m
//  ELife
//
//  Created by xiaozhi on 11-5-17.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "GameRechargeController.h"
#import "GameConfirmController.h"
#import "ELifeAppDelegate.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "GameCardModel.h"
#import "GameGoodsInfo.h"
#import "GameListController.h"
#import "GameServerModel.h"
#import "GameChargeParam.h"
#import "GameRootController.h"

@implementation GameRechargeController
@synthesize salevalueLabel, pervalueButton, gameAcountTextField, gameAcountConfirmTextField, qqAcountTextField, qqAcountConfirmTextField, amountsButton, totalLabel, gameServerLabel, gameServerButton, gameAccountLabel, gameAccountConfirmLabel;


#pragma mark - network
- (void)requestServerList
{
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍后"];
    
    NSString *host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSString *urlStr = [host stringByAppendingString:@"ofcard.php"];
    
    static NSString *action = @"get_area_server_list";
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlStr], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:action forKey:@"action"];
    [param setObject:_gameGoodsInfo.cardId forKey:@"game_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [[app httpRequestPoint]openUrl:dic
                         postParam:param target:self];
}

// 隐藏游戏服务器选择相关的控件
- (void)hideServerInputContainer
{
    UIView *otherGameContainer = [self.view viewWithTag:TAG_OTHERVIEW];
    
    // 如果当前的游戏输入区域没有显示则直接返回
    if (otherGameContainer.hidden == YES) {
        return;
    }
    
    const NSInteger OFFSET_Y = -gameServerButton.frame.size.height;
    
    otherGameContainer.frame = CGRectMake(otherGameContainer.frame.origin.x, otherGameContainer.frame.origin.y, otherGameContainer.frame.size.width, otherGameContainer.frame.size.height + OFFSET_Y);
    
    
    gameAccountLabel.frame = CGRectOffset(gameAccountLabel.frame, 0, OFFSET_Y);
    gameAcountTextField.frame = CGRectOffset(gameAcountTextField.frame, 0, OFFSET_Y);
    gameAccountConfirmLabel.frame = CGRectOffset(gameAccountConfirmLabel.frame, 0, OFFSET_Y);
    gameAcountConfirmTextField.frame = CGRectOffset(gameAcountConfirmTextField.frame, 0, OFFSET_Y);
    
    [gameServerLabel setHidden:YES];
    [gameServerButton setHidden:YES];
}

- (void)iRequestFinished:(NSData *)response
{
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    //    NSLog(@"--------body:%@", bodyElement);
    //某个具体节点的文本内容
    GDataXMLElement* gamesElement = [[bodyElement elementsForName:@"area_list"]objectAtIndex:0];
    NSLog(@"--------goods_list:%@", gamesElement);
    
    // 如果没有区服
    if (gamesElement == nil) {
        [self hideServerInputContainer];
        // 隐藏进度条
        ELifeAppDelegate *app = [ELifeAppDelegate App];
        [app hideProgressDialog];
        return;
    }
    
    NSArray *gameArr = [gamesElement children];
    _gameServerList = [[NSMutableArray alloc]initWithCapacity:[gameArr count]];
    static NSString *SPLITE_CHAR = @",";
    for (int i = 0; i<[gameArr count]; i++) {
        GDataXMLElement *item = [gameArr objectAtIndex:i];
        NSLog(@"--------item:%@", item);
        NSString *areaName = [[[item elementsForName:@"area_name"]objectAtIndex:0]stringValue];
        NSString *serverListStr = [[[item elementsForName:@"server_list"]
                                    objectAtIndex:0]stringValue];
        
        if ([serverListStr length] > 0) {
            NSLog(@"--------serverListStr:%@", serverListStr);
        }
                
        NSRange range = [serverListStr rangeOfString:SPLITE_CHAR];
        NSArray *serverList = nil;
        if (range.location != NSNotFound) {
            serverList = [serverListStr componentsSeparatedByString:SPLITE_CHAR];
        }
        
        // 生成model
        GameServerModel *serverModel = [[GameServerModel alloc]init];
        serverModel.areaName = areaName;
        serverModel.serverList = serverList;
        
        [_gameServerList addObject:serverModel];
        
        NSLog(@"--------areaName:%@", areaName);
        NSLog(@"--------serverList:%@", serverList);
    }
    
    // 隐藏进度条
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app hideProgressDialog];
    
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

// 计算总价
- (void)calTotalPay
{
    NSInteger total = [_gameGoodsInfo.salevalue intValue] * [[amountsButton titleForState:UIControlStateNormal] intValue];
    NSString *totalText = [NSString stringWithFormat:@"%d", total];
    
    [totalLabel setText:totalText];
}

- (void)initWithGoodsInfo:(GameGoodsInfo *)goodsInfo
{
    NSString *pervalueText = [goodsInfo.pervalue stringByAppendingString:@"元"];
    [pervalueButton setTitle:pervalueText forState:UIControlStateNormal];
    
    NSString *salevalueText = [goodsInfo.salevalue stringByAppendingString:@"元"];
    [salevalueLabel setText:salevalueText];
    
    [self calTotalPay];
}

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil state:(GameListType)chargeState goodsInfo:(GameGoodsInfo *)goodsInfo
{
    self = [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _gameGoodsInfo = goodsInfo;
        _chargeState = chargeState;
        UIView *subView = nil;
        switch (chargeState) {
            case STATE_QQ:
                subView = [self.view viewWithTag:TAG_QQVIEW];
                break;
            case STATE_OTHER:
                subView = [self.view viewWithTag:TAG_OTHERVIEW];
                break;
            default:
                subView = [self.view viewWithTag:TAG_QQVIEW];
                break;
        }
        
        NSInteger OFFSET_Y = 15;
        
        // set diffrent view x y
        UIView *commView = [self.view viewWithTag:TAG_COMM_VIEW];
        CGRect commFrame = commView.frame;
        commView.layer.cornerRadius = 8;
        commView.layer.masksToBounds = YES;
        
        NSInteger subViewX = commFrame.origin.x;
        NSInteger subViewY = commFrame.origin.y + commFrame.size.height + OFFSET_Y;

        subView.frame = CGRectMake(subViewX, subViewY, subView.frame.size.width, subView.frame.size.height);
        subView.layer.cornerRadius = 8;
        subView.layer.masksToBounds = YES;
        [subView setHidden:NO];
        
        
        // set button xy
        UIView *button = [self.view viewWithTag:TAG_COMM_BUTTON];
        NSInteger buttonX = subViewX;
        NSInteger buttonY = subViewY + subView.frame.size.height + OFFSET_Y;
        button.frame = CGRectMake(buttonX, buttonY, button.frame.size.width, button.frame.size.height);
        
        [self initWithGoodsInfo:goodsInfo];
        
        // 请求服务器列表
        [self requestServerList];
    }
    return self;
}

- (void)dealloc
{
    [_chargeParam release];
    [gameAccountConfirmLabel release];
    [gameAccountLabel release];
    [gameServerLabel release];
    [gameServerButton release];
    [totalLabel release];
    [amountsButton release];
    [_gameServerList release];
    [pervalueButton release];
    [salevalueLabel release];
    [gameAcountTextField release];
    [gameAcountConfirmTextField release];
    [qqAcountTextField release];
    [qqAcountConfirmTextField release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)showSpinner:(NSArray *)spinnerList
{
    //　hide tabbar
    UIActionSheet *spinner = [[UIActionSheet alloc]initWithTitle:@"请选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    
    for (NSInteger index = 0; index < [spinnerList count]; index++) {
        [spinner addButtonWithTitle:[spinnerList objectAtIndex:index]];
    }
    [spinner addButtonWithTitle:@"cancel"];
    
    spinner.cancelButtonIndex = [spinnerList count];
    
    [spinner showInView:self.view];
    [spinner release];

}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex < [_gameGoodsInfo.amounts count]) {
        NSString *text = [_gameGoodsInfo.amounts objectAtIndex:buttonIndex];
        [amountsButton setTitle:text forState:UIControlStateNormal];
        [self calTotalPay];
    }
    
}

// open game list
-(void)openSeverList
{
    GameListController  *gameListController = [[GameListController alloc] initWithNibName:@"GameListcontroller" bundle:nil];
    
    [gameListController setListener:self];
    [self.navigationController pushViewController:gameListController animated:YES];
    [gameListController release];
}

-(IBAction)pickGameServer 
{
    _isSecondList = NO;
    [self openSeverList];
}

-(void)openSpinner:(id)sender
{
    [self showSpinner:_gameGoodsInfo.amounts];
}

#pragma mark - serverListDelegate
- (NSString *)getCellName:(NSInteger)index
{
    if (_isSecondList) {
        NSString *serverName = [_selectedGameServerModel.serverList objectAtIndex: index];
        return serverName;
    }
    
    GameServerModel *serverModel = [_gameServerList objectAtIndex:index];
    return serverModel.areaName;
    
}

- (BOOL)hasNextLevel:(NSInteger)index
{
    GameServerModel *model = [_gameServerList objectAtIndex:index];
    NSArray *serverList = model.serverList;
        if (_isSecondList == NO
        && serverList != nil) {
        return YES;
    }
    return NO;
}

- (void)setServerInfo:(NSString *)area serverName:(NSString *)serverName
{
    _chargeParam = [[GameChargeParam alloc]init];
    _chargeParam.area = area;
    _chargeParam.server = serverName;
    
    NSString *buttonTitle = area;
    if (serverName != nil) {
        buttonTitle = [area stringByAppendingFormat:@" - %@", serverName];
    }    
    [gameServerButton setTitle:buttonTitle forState:UIControlStateNormal];
}

- (void)didSelected:(NSInteger)index
{
    NSArray *serverList = _selectedGameServerModel.serverList;
    if (_isSecondList == YES) {
        _selectedServer = [serverList objectAtIndex:index];
        [self setServerInfo:_selectedGameServerModel.areaName serverName:_selectedServer];
        
        [self.navigationController popToViewController:self animated:YES];
    } else {
        _selectedGameServerModel = [_gameServerList objectAtIndex:index];
        // 打开下级列表
        if (_isSecondList == NO && serverList != nil) {
            _isSecondList = YES;
            [self openSeverList];
        } else {
#pragma mark - 设置选中的服务器信息
            // 设置选中的服务器
            [self setServerInfo:_selectedGameServerModel.areaName serverName:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (NSInteger)getCount
{
    if (_isSecondList) {
        GameServerModel *selectedModel = _selectedGameServerModel;
        return [selectedModel.serverList count];
    }
    return [_gameServerList count];
}


#pragma markend
- (BOOL)isEmpty:(UITextField *)textField
{
    NSString *text = textField.text;
    if (text == nil || [text length] == 0) {
        return YES;
    }
    return NO;
}

- (NSInteger)inputValidate
{
    NSInteger resultCode = INPUT_VALIDATE_CODE_OK;
    NSString *serverName = gameServerButton.titleLabel.text;
    switch (_chargeState) {
        case STATE_QQ:
            if ([self isEmpty:qqAcountTextField]) {
                resultCode = INPUT_VALIDATE_CODE_ACCOUNT_EMPTY;
            } else if([self isEmpty:qqAcountConfirmTextField]) {
                resultCode = INPUT_VALIDATE_CODE_CONFIRM_EMPTY;
            }
            break;
        case STATE_OTHER:
            if ([self isEmpty:gameAcountTextField]) {
                resultCode = INPUT_VALIDATE_CODE_ACCOUNT_EMPTY;
            } else if([self isEmpty:gameAcountConfirmTextField]) {
                resultCode = INPUT_VALIDATE_CODE_CONFIRM_EMPTY;
            } else if([gameAcountConfirmTextField.text isEqualToString:gameAcountTextField.text] == NO) {
                resultCode = INPUT_VALIDATE_CODE_DIFF;
            } else if(serverName == nil || [serverName length] == 0) {
                resultCode = INPUT_VALIDATE_CODE_SERVER_EMPTY;
            }
            break;
        default:
            break;
    }    
    return resultCode;
}

- (void)showAlertDialog:(NSString *)msg
{
    // show dialog
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:msg delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}

// 生成查询需要的param
- (GameChargeParam *)buildChargeParam
{
    GameChargeParam *param = [[GameChargeParam alloc]init];
    param.goodsId = _gameGoodsInfo.cardId;
    param.area = _selectedGameServerModel.areaName;
    param.server = _selectedServer;
    param.goodsNum = [amountsButton titleForState:UIControlStateNormal];
    param.userId = gameAcountTextField.text;
    param.money = totalLabel.text;
    return param;
}

-(void)confirm
{
    NSInteger validateCode = [self inputValidate];
    if (validateCode != INPUT_VALIDATE_CODE_OK) {
        NSString *msg = @"帐号前后不一致";
        switch (validateCode) {
            case INPUT_VALIDATE_CODE_ACCOUNT_EMPTY:
                msg = @"帐号不能为空";
                break;
            case INPUT_VALIDATE_CODE_CONFIRM_EMPTY:
                msg = @"帐号确认不能为空";
                break;  
            case INPUT_VALIDATE_CODE_SERVER_EMPTY:
                msg = @"服务器不能为空";
                break;
            default:
                break;
        }
        [self showAlertDialog:msg];
        return;
    }
    
    // 进入到支付确认页面
    GameConfirmController *controller = [[GameConfirmController alloc]initWithNibName:@"GameConfirmController" bundle:nil chargeParam:[self buildChargeParam] goodsInfo:_gameGoodsInfo];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

-(void)inputFinished
{
    [gameAcountConfirmTextField resignFirstResponder];
    [gameAcountTextField resignFirstResponder];
    [qqAcountConfirmTextField resignFirstResponder];
    [qqAcountTextField resignFirstResponder];
}
@end
